<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>汽车智问</h1>
      <p class="subtitle">有任何车型问题，随时咨询我</p>
    </div>

    <div class="chat-messages" ref="chatMessages">
      <!-- 欢迎消息 -->
      <div class="message ai-message" v-if="messages.length === 0">
        <div class="message-content">
          <p>您好！我是汽车智问助手，请问有什么车型信息可以帮您查询或推荐？</p>
        </div>
      </div>

      <!-- 消息列表 -->
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.sender === 'user' ? 'user-message' : 'ai-message']"
      >
        <div class="message-content">
          <p v-if="message.sender === 'user'">{{ message.content }}</p>
          <p v-else-if="message.type === 'chat'">{{ message.content }}</p>
          <div v-else-if="message.type === 'buy'" class="car-card">
            <h3>{{ message.content.brand }} {{ message.content.model }}</h3>
            <div class="car-details">
              <p><strong>价格:</strong> {{ message.content.price }}万元</p>
              <p><strong>座位数:</strong> {{ message.content.seats }}座</p>
              <p><strong>动力类型:</strong> {{ message.content.power_type }}</p>
              <p v-if="message.content.battery_capacity"><strong>电池容量:</strong> {{ message.content.battery_capacity }}kWh</p>
              <p v-if="message.content.range"><strong>续航里程:</strong> {{ message.content.range }}km</p>
              <div v-if="message.content.features && message.content.features.length"><strong>车辆特征:</strong>
                <div class="features-list">
                  <span v-for="(feature, index) in message.content.features" :key="index">{{ feature }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else-if="message.type === 'recommendation'">
            <h4>{{ message.content.title }}</h4>
            <p>{{ message.content.description }}</p>
            <div class="car-specs">
              <div
                class="spec-item"
                v-for="(spec, i) in message.content.specs"
                :key="i"
              >
                {{ spec }}
              </div>
            </div>
          </div>
        </div>
        <div class="message-time">{{ message.timestamp }}</div>
      </div>

      <!-- 加载状态 -->
      <div class="message ai-message" v-if="loading">
        <div class="message-content loading-content">
          <div class="typing-indicator">
            <span></span><span></span><span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <textarea
        v-model="userQuery"
        @keyup.enter.exact="sendMessage"
        @keyup.enter.shift="addNewline"
        placeholder="输入您的问题，按Enter发送..."
        :disabled="loading"
      ></textarea>
      <button
        @click="sendMessage"
        :disabled="!userQuery.trim() || loading"
        class="send-btn"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import api from '@/api/index';

const userQuery = ref('');
const messages = ref([]);
const loading = ref(false);
const chatMessages = ref(null);
const user = JSON.parse(localStorage.getItem('userInfo') || '{}');
const userId = user.userId;

const sendMessage = async () => {
  if (!userQuery.value.trim() || loading.value) return;

  // 添加用户消息
  const userMessage = {
    sender: 'user',
    content: userQuery.value,
    timestamp: formatTime(new Date())
  };
  messages.value.push(userMessage);
  scrollToBottom();

  // 清空输入框
  userQuery.value = '';
  loading.value = true;

  try {
    // 调用AI接口发送消息
    const response = await api.sendMessage({
      userId: userId,
      question: userMessage.content
    });

    console.log('AI回复:', response.data);
    let aiResponse = response.data;
    // 处理响应
    if (typeof aiResponse === 'string') {
      try {
        // 尝试解析为JSON
        aiResponse = JSON.parse(aiResponse);
      } catch (e) {
        console.error('解析AI响应失败，将作为纯文本处理:', e);
        // 直接将字符串作为内容
        aiResponse = { type: 'chat', content: aiResponse };
      }
    } else if (typeof aiResponse !== 'object') {
      // 确保aiResponse是对象
      aiResponse = { type: 'chat', content: String(aiResponse) };
    }

    // 确保type属性存在
    if (!aiResponse.type) {
      aiResponse.type = 'chat';
    }

    // 添加AI回复
    messages.value.push({
      sender: 'ai',
      type: aiResponse.type,
      content: aiResponse.content,
      timestamp: formatTime(new Date())
    });
  } catch (error) {
    messages.value.push({
      sender: 'ai',
      content: '抱歉，当前服务不可用，请稍后再试。',
      timestamp: formatTime(new Date())
    });
    console.error('AI对话错误:', error);
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

const addNewline = () => {
  userQuery.value += '\n';
};

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessages.value) {
      chatMessages.value.scrollTo({
        top: chatMessages.value.scrollHeight,
        behavior: 'smooth'
      });
    }
  });
};

const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};

const generateAIResponse = (query) => {
  const lowerQuery = query.toLowerCase();

  if (lowerQuery.includes('suv') || lowerQuery.includes('运动型多用途车')) {
    return {
      type: 'recommendation',
      content: {
        title: '推荐SUV车型',
        description: '根据您的需求，以下是几款适合的SUV车型推荐：',
        specs: [
          '车型A - 20万左右 | 1.5T发动机 | 自动变速箱 | 全景天窗',
          '车型B - 25万左右 | 2.0T发动机 | 四驱系统 | 智能驾驶辅助',
          '车型C - 18万左右 | 混合动力 | 省油耐用 | 大空间'
        ]
      }
    };
  } else if (lowerQuery.includes('轿车') || lowerQuery.includes('sedan')) {
    return {
      type: 'recommendation',
      content: {
        title: '推荐轿车车型',
        description: '根据您的需求，以下是适合您的轿车车型推荐：',
        specs: [
          '车型D - 15万左右 | 1.8L发动机 | CVT变速箱 | 舒适内饰',
        ]
      }
    };
  } else if (lowerQuery.includes('价格') || lowerQuery.includes('预算')) {
    return {
      content: '请告诉我您的具体预算范围和车型偏好，我会为您推荐最适合的车型。'
    };
  } else {
    return {
      content: '感谢您的咨询！为了给您更精准的推荐，请提供以下信息：\n1. 预算范围\n2. 车型偏好（轿车/SUV/其他）\n3. 主要用途（家庭/通勤/越野等）\n4. 特别关注的配置或性能'
    };
  }
};

onMounted(() => {
  console.log('1111:', userId)
  // 初始化聊天会话（使用临时用户ID，实际项目中应替换为真实用户ID）
  api.startChatSession(userId).then(() => {
    console.log('AI聊天会话初始化成功');
  }).catch(err => {
    console.error('会话初始化失败:', err);
  });
  scrollToBottom();
});
</script>

<style scoped>
.chat-container {
  max-width: 100%;
  margin: 0;
  height: 80vh;
  display: flex;
  flex-direction: column;
  background-color: #1a1a1a;
  color: #e0e0e0;
}

.chat-header {
  background-color: #1a1a1a;
  color: white;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.subtitle {
  font-size: 0.9rem;
  opacity: 0.9;
  margin-top: 0.5rem;
}

.chat-messages {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #555;
  border-radius: 4px;
}

.message {
  max-width: 75%;
  display: flex;
  flex-direction: column;
}

.user-message {
  align-self: flex-end;
}

.ai-message {
  align-self: flex-start;
}

.message-content {
  padding: 0.8rem 1.2rem;
  border-radius: 18px;
  position: relative;
  word-break: break-word;
}

.user-message .message-content {
  background-color: #0066cc;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-content {
  background-color: #3d3d3d;
  color: #e0e0e0;
  border: 1px solid #444;
  border-bottom-left-radius: 4px;
}

.message-time {
  font-size: 0.7rem;
  margin-top: 0.3rem;
  opacity: 0.7;
  align-self: flex-end;
}

.chat-input-area {
  display: flex;
  padding: 1rem;
  background-color: #2d2d2d;
  border-top: 1px solid #444;
  gap: 0.5rem;
}

textarea {
  flex: 1;
  border: 1px solid #555;
  border-radius: 20px;
  padding: 0.8rem 1.2rem;
  resize: none;
  font-size: 1rem;
  min-height: 40px;
  max-height: 120px;
  background-color: #3d3d3d;
  color: #e0e0e0;
}

textarea:focus {
  outline: none;
  border-color: #0066cc;
}

.send-btn {
  background-color: #0066cc;
  color: white;
  border: none;
  border-radius: 50%;
  width: 44px;
  height: 44px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.send-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.loading-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.typing-indicator {
  display: flex;
  gap: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #ccc;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.car-specs {
  margin-top: 0.8rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.spec-item {
  font-size: 0.9rem;
  padding: 0.4rem 0.8rem;
  background-color: #3d3d3d;
  border-radius: 4px;
  color: #e0e0e0;
}

.car-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px;
  margin-top: 10px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.car-card h3 {
  margin: 0 0 12px 0;
  color: #1e293b;
  font-size: 18px;
}

.car-details p {
  margin: 8px 0;
  color: #475569;
  font-size: 14px;
}

.car-details strong {
  color: #0f172a;
}

.features-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.features-list span {
  background-color: #e1f5fe;
  color: #0288d1;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>